package com.lambkit.db;

import cn.hutool.core.util.StrUtil;
import com.lambkit.util.Printer;

import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yangyong(孤竹行)
 */
public class DbPool {
    private static final ConcurrentHashMap<String, IDb> pool = new ConcurrentHashMap<String, IDb>();
    private static final ConcurrentHashMap<String, DbConfig> configs = new ConcurrentHashMap<String, DbConfig>();
    private static String defaultName;

    public static final String DEFAULT_NAME = "main";

    public static IDb use() {
        return use(defaultName);
    }

    public static IDb use(String name) {
        if(StrUtil.isBlank(name)) {
            name = DEFAULT_NAME;
        }
        return pool.get(name);
    }

    public static boolean add(String name, IDb opt) {
        if(StrUtil.isBlank(name)) {
            name = DEFAULT_NAME;
        }
        if(pool.containsKey(name)) {
            return false;
        }
        if(StrUtil.isBlank(defaultName)) {
            defaultName = name;
        }
        pool.put(name, opt);
        Printer.print(DbPool.class, "stater", "DbPool add " + name + " success! This Db used dialect class is " + opt.getDialect().getClass().getName());
        return true;
    }

    public static void add(DbConfig dbConfig) {
        configs.put(dbConfig.getName(), dbConfig);
    }
    public static DbConfig config(String name) {
        return configs.get(name);
    }

    public static void remove(String name) {
        pool.remove(name);
        configs.remove(name);
    }

    public static String getDefaultName() {
        return defaultName;
    }

    public static void setDefaultName(String name) {
        defaultName = name;
    }
}
